package com.zz.inventory.config;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.redis.service.RedisService;
import com.zz.inventory.domain.Classes;
import com.zz.inventory.domain.Students;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SchoolRedisService {
    @Autowired
    private RedisService redisService;
    private static final String CLASS_KEY_PREFIX = "school:class:";
    private static final String STUDENT_KEY_PREFIX = "school:student:";
    private static final String CLASS_STUDENTS_KEY_PREFIX = "school:class_students:";
    private static final long CACHE_EXPIRE_HOURS = 1;


    // 班级操作
    public void cacheClass(Classes classes) {
        String key = CLASS_KEY_PREFIX + classes.getClassId();
        redisService.setCacheObject(key,classes,CACHE_EXPIRE_HOURS,TimeUnit.HOURS);
    }

    public Classes getCachedClass(Long classId) {
        try {
            String key = CLASS_KEY_PREFIX + classId;
            Object cached = redisService.getCacheObject(key);

            if (cached instanceof Classes) {
                return (Classes) cached;
            }
            if (cached instanceof JSONObject) {
                // FastJson2反序列化处理
                return ((JSONObject)cached).toJavaObject(Classes.class);
            }

            log.warn("缓存数据类型不匹配，key: {}, 类型: {}", key, cached != null ? cached.getClass() : "null");
            return null;
        } catch (Exception e) {
            log.error("获取班级缓存异常", e);
            return null;
        }
    }

    public void removeCachedClass(Long classId) {
        String key = CLASS_KEY_PREFIX + classId;
        redisService.deleteObject(key);

        // 同时删除班级学生列表缓存
        String classStudentsKey = CLASS_STUDENTS_KEY_PREFIX + classId;
        redisService.deleteObject(classStudentsKey);
    }

    // 学生操作
    public void cacheStudent(Students student) {
        try {
            if (student == null || student.getStudentId() == null) {
                log.warn("尝试缓存无效学生数据: {}", student);
                return;
            }

            String key = STUDENT_KEY_PREFIX + student.getStudentId();
            redisService.setCacheObject(key, student, CACHE_EXPIRE_HOURS, TimeUnit.HOURS);
            log.debug("成功缓存学生: {}", key);
        } catch (Exception e) {
            log.error("缓存学生失败 ID:{}", student != null ? student.getStudentId() : "null", e);
        }
    }

    public Students getCachedStudent(Long studentId) {
        String key = STUDENT_KEY_PREFIX + studentId;
        return redisService.getCacheObject(key);
    }

    public void removeCachedStudent(Long studentId) {
        Students student = getCachedStudent(studentId);
        if (student != null) {
            // 从班级学生集合中移除
            if (student.getClassId() != null) {
                String classStudentsKey = CLASS_STUDENTS_KEY_PREFIX + student.getClassId();
                redisService.deleteObject(classStudentsKey);
            }

            // 删除学生缓存
            String studentKey = STUDENT_KEY_PREFIX + studentId;
            redisService.deleteObject(studentKey);
        }
    }

    // 获取班级所有学生ID
    public List<Long> getClassStudentIds(Long classId) {
        String key = CLASS_STUDENTS_KEY_PREFIX + classId;
        Set<Long> members = redisService.getCacheSet(key);
        return members != null ? List.copyOf(members) : Collections.emptyList();
    }

    public void batchCacheClasses(List<Classes> classesList) {
        classesList.forEach(this::cacheClass);
    }

    public void batchCacheStudents(List<Students> studentsList) {
        studentsList.forEach(this::cacheStudent);
    }

    // 添加清理方法
    /*public void cleanInvalidCache() {
        String nullKey = STUDENT_KEY_PREFIX + "null";
        if (redisService.hasKey(nullKey)) {
            redisService.deleteObject(nullKey);
            log.info("已清理无效缓存键: {}", nullKey);
        }
    }*/
}
